package com.vakitdaraliyor.www.dao;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.vakitdaraliyor.www.entity.Role;

@Stateless
public class RoleDao {

	@PersistenceContext
	private EntityManager entityManager;
	
	public Role kullaniciGetirById(Integer id) {
		return (Role) entityManager
				.createQuery("select a from Role a where a.id =:id")
				.setParameter("id", id).getSingleResult();
	}
	
	public Role getRoleByRoleName(String rolename) {

		try {
			return (Role) entityManager
					.createQuery(
							"select i from Role i where i.roleName =:rolename")
					.setParameter("rolename", rolename)
					.getSingleResult();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			return null;
		}
	}
	
	public Role registerRole(Role role){
		entityManager.persist(role);
		return role;
	}
	
	public Role deleteRole(Role role){
		if (entityManager.contains(role)) {
			entityManager.remove(role);
			return role;
		} else {
			Role newRole = entityManager.merge(role);
			entityManager.remove(newRole);
			return newRole;
		}
	}
	
	public Role updateRole(Role role) {
		entityManager.merge(role);
		return role;
	}
	
	
	
}
